<template>
  <div class="article-list">
    <van-pull-refresh success-duration="1500"
      :success-text="tipText"
      v-model="pullRefreshIsLoading"
      @refresh="onRefresh">
      <van-list :error.sync="error"
        error-text="请求失败，点击重新加载" v-model="loading"
        :finished="finished" finished-text="没有更多了"
        @load="onLoad">
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
        <article-item v-for="item in list"
          :key="item.art_id+''" :article="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import ArticleItem from '@/components/article/article-item.vue'
export default {
  name: 'article-list',
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      pre_timestamp: Date.now(),
      error: false,
      pullRefreshIsLoading: false,
      tipText: ''
    }
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data: res } = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.pre_timestamp,
          with_top: 0
        })
        // if (Math.random() > 0.5) {
        //   console.lg(123)
        // }
        this.list.push(...res.data.results)
        this.pre_timestamp = res.data.pre_timestamp
        // 加载状态结束
        this.loading = false
        if (res.data.results.length === 0) {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const { data: res } = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 0
        })
        // if (Math.random() > 0.5) {
        //   console.lg(123)
        // }
        this.list.unshift(...res.data.results)
        this.pullRefreshIsLoading = false
        this.tipText = '加载成功，一共加载了' + res.data.results.length + '条数据'
      } catch (err) {
        this.pullRefreshIsLoading = false
        this.tipText = '加载失败,请重试'
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    ArticleItem
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.article-list {
  height: 80vh;
  overflow-y: scroll;
}
</style>
